import "@/styles/vditor/index.css";
import { HTMLAttributes, useEffect, useRef } from "react";
import Vditor from "vditor";
import { log_error } from "../Main/log_error";
import { v4 as uuid } from "uuid";
import devices from "current-device"
export namespace VditorView {
  export interface IUploader {
    (file: File): Promise<string>;
  }
}

export interface IVditorViewProps extends Omit<HTMLAttributes<HTMLDivElement>, 'lang'> {
  editor?: Vditor;
  className?: string;
  uploader?: VditorView.IUploader;
  options?: IOptions;
  height?: IOptions['height'];
  cdn?: IOptions['cdn'];
  mode?: IOptions['mode'];
  on_ready?(editor: Vditor): void;
}
const default_mode = devices.desktop() ? 'sv' : 'ir';

export function VditorView(props: IVditorViewProps) {
  const ref_div = useRef<HTMLDivElement>(null);
  const {
    className,
    style,
    uploader,
    height = 0,
    cdn,
    mode = default_mode,
    on_ready
  } = props

  const ref_after = useRef(on_ready);
  ref_after.current = on_ready;

  useEffect(() => {
    const div = ref_div.current
    if (!div) return;
    let editor: Vditor | undefined = void 0;
    const options: IOptions = {
      upload: {
        accept: "image/jpeg,image/png,image/gif,image/webp",
        handler: async (files): Promise<any> => {
          if (!uploader) return 'uploader not set'
          try {
            for (const file of files) {
              const url = await uploader(file);
              editor?.insertValue(`![${file.name}](${url})`);
            }
            return null;
          } catch (e) {
            log_error(e);
            return e instanceof Error ? e.message : '' + e
          }
        },
      },
      cache: { id: uuid() },
      height,
      cdn: cdn || `${window.location.protocol}//${window.location.host}/lib/vditor`,
      mode,
      after: () => ref_after.current?.(editor!),
      input(e) {
        // console.log(e)
        // const vditor = editor?.vditor;
        // if (!vditor) return;

        // if (e.key.toLowerCase() === 'enter') {
        //   vditor.undo?.addToUndoStack(vditor)
        // }
        // if (e.key.toLowerCase() === 'space') {
        //   if (!space_repeating) {
        //     vditor.undo?.addToUndoStack(vditor)
        //   }
        //   space_repeating = true
        // } else if (space_repeating) {
        //   space_repeating = false;
        //   vditor.undo?.addToUndoStack(vditor)
        // }
      }
    }
    editor = new Vditor(div, options);
    return () => { try { editor.destroy() } catch (e) { } };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <div
      ref={ref_div}
      className={className}
      style={style}
    />
  )
}